<?php

declare(strict_types=1);

namespace app\xapply\controller;

use app\xapply\middleware\Auth;
use app\xapply\Xapply;
use app\xapply\model\Message as MessageModel;
use app\xapply\model\App;
use app\xapply\model\Rule;
use app\xapply\Push;
use app\xapply\model\Login;

class Message extends Xapply
{

    protected $middleware = [Auth::class];

    /**
     * 时间转换
     * @param int $timestamp 时间戳
     * @return string 转换后的时间格式
     */
    private function timeAgo($timestamp)
    {
        $currentTime = time();
        $date = date('Y-m-d', $timestamp);
        $date2 = date('Y-m-d', $currentTime);
        if ($date == $date2) {
            return date('H:i', $timestamp);
        } elseif (date('Y', $currentTime) == date('Y', $timestamp)) {
            return date('m-d H:i', $timestamp);
        } else {
            return date('Y-m-d H:i', $timestamp);
        }
    }
    
    /**
     * 消息列表
     * url: http://域名/xapply/message/list
     * doc: http://lutui.net/doc/app/message-list.html
     */
    public function list()
    {
        $user = $this->getUserinfo();
        $apps = MessageModel::group('app_id')->column('app_id');
        $list = App::with([
            'messages' => function ($query) use ($user) {
                $query->where('to_uid', $user['id'])->order('id', 'desc')->limit(1);
            }
        ])->withCount([
            'messages' => function ($query) use ($user) {
                $query->where('to_uid', $user['id'])->where('unread', 1);
            }
        ])->where('id', 'in', $apps)->select();
        $new = [];
        foreach ($list as $item) {
            $message = $item['messages'][0];
            $count = 0;
            if (Rule::getPerm($user, $item, 2)){
                $count = MessageModel::where('app_id', $item->id)->where('to_uid', $user['id'])->where('wfr', 1)->count();
            }
            $new[] = [
                'id' => $item->id,
                'name' => $item->name,
                'url' => $item->icon,
                'content' => $message->title,
                'wfr' => $count > 0 ? true : false,
                'messages' => $item->messages_count,
                'time' => $this->timeAgo(strtotime($message->create_time)),
                'app' => 'app://' . $item->app_name,
            ];
        }
        return json($new);
    }

    /**
     * 查看应用消息
     * url: http://域名/api/v1/message/view
     * doc: http://lutui.net/doc/app/message-view.html
     */
    public function view()
    {
        $id = $this->data['id'];
        $page = $this->data['page'];
        $tpp = 20;
        $start = ($page - 1) * $tpp;
        $user = $this->getUserinfo();
        $list = MessageModel::with(['from'])->where('to_uid', $user['id'])->where('app_id', $id)->order('id', 'desc')->limit($start, $tpp)->select();
        $new = [];
        foreach ($list as $item) {
            $thumb = $item->from->thumb;
            if (!strstr($thumb, 'http')){
                $thumb = request()->domain().$thumb;
            }
            $new[] = [
                'id' => intval($item->id),
                'name' => $item->from->nickname,
                'url' => $thumb,
                'content' => $item->content,
                'time' => $this->timeAgo(strtotime($item->create_time)),
                'wfr' => $item->wfr == 1 ? true : false,
                'resolve' => $item->resolve ? $item->resolve : ($item->wfr == 1 ? '审核通过' : ''),
                'reject' => $item->reject ? $item->reject : ($item->wfr == 1 ? '驳回' : ''),
            ];
        }
        // 更新已读状态
        MessageModel::where('app_id', $id)->where('unread', 1)->where('to_uid', $user['id'])->update(['unread' => 0]);
        // 发送穿透消息
        $token = Login::where('user_id', $user['id'])->value('push');
        if ($token){
            Push::message([$token]);
        }
        return json($new);
    }

    /**
     * 自定义菜单
     * url: http://域名/xapply/message/menu
     * doc: http://lutui.net/doc/app/message-menu.html
     */
    public function menu()
    {
        return '';
    }

    /**
     * 消息的操作
     * url: http://域名/xapply/message/action
     * doc: http://lutui.net/doc/app/message-action.html
     */
    public function action()
    {
        $id = $this->data['id']; // 消息ID
        $command = $this->data['command']; // resolve=审批通过, reject=驳回请求
        $message = MessageModel::find($id);
        if (empty($message)) {
            return json(['error' => '消息不存在']);
        }
        $app =  App::find($message->app_id);
        if (empty($app)) {
            return json(['error' => '应用不存在']);
        }
        $user = $this->getUserinfo();
        $allow = Rule::getPerm($user, $app, 2);
        if (!$allow) {
            return json(['error' => '没有权限操作']);
        }
        // ...

        // ...
        return json(['error' => '未定义操作方法']);
    }
}
